package qywxrobot

import (
	"bytes"
	json2 "encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
)

type QYWXRobot struct {
	Robot   string  `json:"robot"`
	QYWXMsg QYWXMsg `json:"qywx_msg"`
}

// QYWXMsg 企业微信机器人消息内容
type QYWXMsg struct {
	Msgtype  string   `json:"msgtype"`
	Markdown Markdown `json:"markdown"`
}

type Markdown struct {
	Content string `json:"content"`
}

type QYWXResponse struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
}

//Json 将发送内容序列化
func (qywxmsg QYWXMsg) Json() []byte {
	json, err := json2.Marshal(qywxmsg)
	if err != nil {
		return nil
	}
	return json
}

//MsgSend 发送企业微信机器人消息
func (r *QYWXRobot) MsgSend() (int, error) {

	req, err := http.NewRequest("POST", r.Robot, bytes.NewReader(r.QYWXMsg.Json()))
	if err != nil {
		return 2, err
	}

	resp, err := DoRequest(req)
	if err != nil {
		return 3, err
	}

	defer func(Body io.ReadCloser) {
		_ = Body.Close()
	}(resp.Body)

	if resp.Status != "200 OK" {
		return 4, fmt.Errorf("http response code error: %s", resp.Status)
	}
	respbody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 5, err
	}
	body := new(QYWXResponse)
	err = json2.Unmarshal(respbody, body)
	if body.Errcode != 0 {
		return 1, fmt.Errorf("企业微信机器人接口调用失败: %s", body.Errmsg)
	} else {
		return 0, nil
	}
	//} else {
	//	return 2, fmt.Errorf("企业微信机器人接口http返回状态错误：%s\n", resp.Status)
	//}
}

func DoRequest(req *http.Request) (*http.Response, error) {
	//defer func() {
	//	if err := recover(); err != nil {
	//		fmt.Printf("recover form panic: %s", err)
	//	}
	//}()

	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	return resp, nil

	//defer func(Body io.ReadCloser) {
	//	_ = Body.Close()
	//}(resp.Body)
}
